package org.jctc.els.modules.biz.service.team.impl;

import cn.hutool.core.util.BooleanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.AllArgsConstructor;
import org.jctc.els.modules.biz.entity.ElsUserProject.ElsUserProject;
import org.jctc.els.modules.biz.entity.elsTeamMembers.ElsTeamMembers;
import org.jctc.els.modules.biz.entity.elsTeamProject.ElsTeamProject;
import org.jctc.els.modules.biz.entity.pro.ElsProjectReview;
import org.jctc.els.modules.biz.entity.team.Team;
import org.jctc.els.modules.biz.mapper.elsTeamMembers.ElsTeamMembersMapper;
import org.jctc.els.modules.biz.mapper.elsTeamProject.ElsTeamProjectMapper;
import org.jctc.els.modules.biz.mapper.elsUserProject.ElsUserProjectMapper;
import org.jctc.els.modules.biz.mapper.pro.ElsProjectReviewMapper;
import org.jctc.els.modules.biz.mapper.team.TeamMapper;
import org.jctc.els.modules.biz.service.team.ITeamService;
import org.jctc.els.modules.biz.vo.TeamVO;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.mp.base.BaseServiceImpl;
import org.springblade.core.tool.utils.Func;
import org.springblade.core.tool.utils.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.List;
import java.util.stream.Collectors;

@Service
@AllArgsConstructor
public class TeamServiceImpl extends BaseServiceImpl<TeamMapper,Team> implements ITeamService {

    @Autowired
    private TeamMapper teamMapper;

    private ElsTeamMembersMapper elsTeamMembersMapper;

    @Autowired
    private ElsProjectReviewMapper elsProjectReviewMapper;

    @Autowired
    private ElsUserProjectMapper userProjectMapper;

    @Autowired
    private ElsTeamProjectMapper teamProjectMapper;

    @Override
    public IPage<TeamVO> selectAllPage(IPage<TeamVO> page, String teamName, Integer teamType) {
        int count = 0;
        String leaderName = "";
        List<TeamVO> teams = teamMapper.selectAllPage(page, teamName, teamType);
        for (TeamVO t: teams) {
            //查询
            ElsTeamMembers elsTeamMembers = elsTeamMembersMapper.selectUserLeader(t.getId().toString());
            if(elsTeamMembers != null){
                count = 1;
                leaderName = elsTeamMembers.getLeaderName();
                t.setLeaderNull(count);
                t.setLeaderName(leaderName);
            }else{
                t.setLeaderNull(0);
                t.setLeaderName("");
            }

        }
        return page.setRecords(teams);
    }



    @Override
    public Team selectById(Long id) {
        Team team = teamMapper.selectByTeamId(id);
        return team;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveOrUpdate(Team team) {

        //return teamMapper.save(team);
        return teamMapper.insert(team) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean update(Team team) {

        Integer count = baseMapper.selectCount(
                Wrappers.<Team>query().lambda()
                        .eq(Team::getName, team.getName())
                        .notIn(Team::getId, team.getId())
        );
        if (count > 0) {
            throw new ServiceException(StringUtil.format("当前小组 [{}] 已存在!", team.getName()));
        }
        return baseMapper.updateById(team) > 0;
    }

    @Override
    public boolean updateTeamLeader(Long userId,String teamId) {
        return teamMapper.updateTeamLeader(userId,teamId) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteTeam(String id) {
        //查询是否有专家进行了打分
        //1.获取小组内的专家
        List<Long> userIdList = elsTeamMembersMapper.selectTeamList(id).stream().map(ElsTeamMembers::getUserId).collect(Collectors.toList());
        if(Func.isNotEmpty(userIdList)) {
            List<ElsProjectReview> projectReviewList = elsProjectReviewMapper.selectList(new QueryWrapper<ElsProjectReview>().in("user_id", userIdList));
            if (projectReviewList.size() > 0) {
                throw new ServiceException("小组内专家对项目进行了评分，不允许删除！");
            }
            //2.判断是否与项目绑定
            List<ElsUserProject> userProjectList = userProjectMapper.selectList(new QueryWrapper<ElsUserProject>().in("user_id", userIdList));
            if (userProjectList.size() > 0) {
                throw new ServiceException("请先将专家与项目进行解绑！");
            }
        }
        List<ElsTeamProject> teamProjectList = teamProjectMapper.selectList(new QueryWrapper<ElsTeamProject>().eq("team_id", id));
        if (teamProjectList.size() > 0) {
            throw new ServiceException("请先将小组与项目进行解绑！");
        }
        Team team = new Team();
        team.setId(Long.parseLong(id));
        team.setIsDeleted(1);
        Boolean result  = teamMapper.updateById(team) > 0;
        if (BooleanUtil.isFalse(result)) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return result;
        }
        return result;
    }
}
